package com.tywj.navigation.tool

import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.amap.api.maps.LocationSource
import com.tywj.lib.core.common.util.AppUtil

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/19
 *     desc   : 自定义实现我的位置定位
 *     version: 1.0.0
 * </pre>
 */
class MyLocation : LocationSource, AMapLocationListener {

    // 高德地图的定位变化监听
    private var aMapLocationChangedListener: LocationSource.OnLocationChangedListener? = null
    private var aMapLocationClient: AMapLocationClient? = null

    // 自定义定位变化监听
    private var onLocationChangedListener: ((AMapLocation) -> Unit)? = null

    override fun activate(listener: LocationSource.OnLocationChangedListener) {
        aMapLocationChangedListener = listener
        if (aMapLocationClient == null) {
            // 初始化定位
            aMapLocationClient = AMapLocationClient(AppUtil.context)
            // 初始化定位参数
            val locationOption = AMapLocationClientOption()
            // 设置连续定位模式下的定位间隔
            locationOption.interval = MapTool.LOCATION_INTERVAL
            // 需要地址信息
            locationOption.isNeedAddress = true
            // 设置定位回调监听
            aMapLocationClient?.setLocationListener(this)
            // 设置为高精度定位模式
            locationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
            // 设置定位参数
            aMapLocationClient?.setLocationOption(locationOption)
            // 启动定位
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            aMapLocationClient?.stopLocation()
            aMapLocationClient?.startLocation()
        }
    }

    override fun deactivate() {
        aMapLocationChangedListener = null
        aMapLocationClient?.let {
            it.stopLocation()
            it.onDestroy()
            aMapLocationClient = null
        }
    }

    override fun onLocationChanged(location: AMapLocation?) {
        if (aMapLocationChangedListener != null && location != null && location.errorCode == 0) {
            // 定位成功
            onLocationChangedListener?.invoke(location)
            aMapLocationChangedListener?.onLocationChanged(location)
        }
    }

    fun onDestroy() {
        aMapLocationClient?.onDestroy()
    }

    fun setOnLocationChangedListener(listener: (location: AMapLocation) -> Unit) {
        onLocationChangedListener = listener
    }
}